package com.yulang.web.controller;

import com.yulang.security.BaseResult;
import com.yulang.web.pojo.SysPermission;
import com.yulang.web.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/permission")
public class SystemPermissionController {

    private static final String HTML_PREFIX = "system/permission/";

    @Autowired
    private SysPermissionService sysPermissionService;

    @PreAuthorize("hasAuthority('sys:permission')")
    @GetMapping(value = {"/",""})
    public String permission(){
        return HTML_PREFIX + "permission-list";
    }

    @ResponseBody
    @PreAuthorize("hasAuthority('sys:permission:list')")
    @PostMapping("/list")
    public BaseResult list(){
        return BaseResult.ok(sysPermissionService.list());
    }

    /**
     * 跳转到新增或修改页面
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:permission:edit','sys:permission:add')")
    @GetMapping({"/form","/form/{id}"})
    public String form(@PathVariable(required = false) Long id, Model model){
        SysPermission sysPermission = new SysPermission();
        if(id!=null){
            sysPermission = sysPermissionService.getById(id);
            Long parentId = sysPermission.getParentId();
            if(parentId!=null){
                SysPermission permission = sysPermissionService.getById(parentId);
                if(permission!=null){
                    sysPermission.setParentName(permission.getName());
                }
            }
        }
        model.addAttribute("permission",sysPermission);
        return HTML_PREFIX + "permission-form";
    }

    /**
     * 跳转到新增或修改页面
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:permission:edit','sys:permission:add')")
    @GetMapping({"/form/child/{id}"})
    public String formChild(@PathVariable Long id, Model model){
        SysPermission sysPermission = new SysPermission();
        SysPermission service = sysPermissionService.getById(id);
        sysPermission.setParentName(service.getName());
        sysPermission.setType(0);
        sysPermission.setParentId(service.getId());
        model.addAttribute("permission",sysPermission);
        return HTML_PREFIX + "permission-form";
    }

    @PreAuthorize("hasAnyAuthority('sys:permission:add','sys:permission:add')")
    @PutMapping
    public String saveOrUpdate(SysPermission sysPermission){
        sysPermissionService.saveOrUpdate(sysPermission);
        return "redirect:/permission";
    }

    @ResponseBody
    @PreAuthorize("hasAuthority('sys:permission:delete')")
    @DeleteMapping("/{id}")
    public BaseResult delete(@PathVariable Long id){
        sysPermissionService.deleteById(id);
        return BaseResult.ok(true);
    }

}
